import axios from "axios";
import { $TipMessage } from "./index";
const { ipcRenderer } = require("electron");

import { useCounterStore } from "../store";
const CryptoJS = require("crypto-js");

console.log("CryptoJS", CryptoJS);
const instance = axios.create({
  // 测试：https://app.xinxin128.com/
  // 线上：https://app.xinxin128.cn/
  baseURL: "https://app.xinxin128.com/",
});

// Add a request interceptor
instance.interceptors.request.use(
  function (config) {
    const notIncludesUrl = ["/server/login/dxlogin"];
    // Do something before request is sent

    if (!notIncludesUrl.includes(config.url)) {
      const store = useCounterStore();

      const token = store.tempOb?.token;
      const uid = store.tempOb?.uid;
      const timestamp = Date.now();
      const deviceCode = store.profile.user.devicecode;

      const signString = `${timestamp}${token}${uid}${deviceCode}${timestamp
        .toString()
        .slice(-6)}`;
      const sign = CryptoJS.MD5(signString).toString();
      console.log("xinxin-sign:", sign);

      config.headers["xinxin-timestamp"] = timestamp;
      config.headers["xinxin-sign"] = sign;
      config.headers["xinxin-devicecode"] =
        deviceCode + timestamp.toString().slice(-6);
    }

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
instance.interceptors.response.use(
  function (response) {
    console.log("response222", response);

    if (response.data.errcode === 2) {
      localStorage.clear();
      ipcRenderer.send("login-out");
      $TipMessage(response.data.errmsg, "error");
    }
    // Do something with response data
    return response;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);
export default instance;
